package tongwentongshu.com.app.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.contract.SearchContract;
import tongwentongshu.com.app.utils.SpUtils;

/**
 * Created by XiongBin on 2017/7/31.
 */

public class SearchActivity extends BaseActivity implements SearchContract.View {
    @BindView(R.id.et_search)
    EditText search;
    @BindView(R.id.ll_data)
    LinearLayout data;
    @BindView(R.id.rv_list)
    ListView mListView;
    List<String> list = new ArrayList<>();
    SearchAdapter searchAdapter;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_search;
    }

    @Override
    protected int getTitleId() {
        return R.string.app_name;
    }

    @Override
    protected void initView() {
        searchAdapter = new SearchAdapter();
        mListView.setAdapter(searchAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle b = new Bundle();
                b.putString("bookname", list.get(position));
                startActivity(SearchResultActivity.class, b);
            }
        });

        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String bookname = "";
                    if (!TextUtils.isEmpty(search.getText().toString().trim())) {
                        bookname = search.getText().toString().trim();
                        if (!getListP(bookname))
                            addData(bookname);
                    }
                    Bundle b = new Bundle();
                    b.putString("bookname", bookname);
                    startActivity(SearchResultActivity.class, b);

                    search.setText("");
                    return true;
                }
                return false;
            }
        });
    }

    String jsonData;

    @Override
    protected void onResume() {
        super.onResume();
        initList();
    }

    boolean getListP(String name) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals(name))
                return true;
        }
        return false;
    }

    void initList() {
        jsonData = SpUtils.getString(mContext, "jsonData", "");
        try {
            if (TextUtils.isEmpty(jsonData)) {
                data.setVisibility(View.GONE);
                return;
            }
            data.setVisibility(View.VISIBLE);
            JSONArray arr = new JSONArray(jsonData);
            list.clear();
            for (int i = 0; i < arr.length(); i++) {
                list.add(arr.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        searchAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tv_cancel, R.id.iv_delete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.rel_deposit:
                search.setText("");
                break;
        }
    }

    class SearchAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                vh = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.view_search, null);
                vh.text = (TextView) convertView.findViewById(R.id.tv_text);
                vh.iv = (ImageView) convertView.findViewById(R.id.iv_delete);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            vh.text.setText(list.get(position));
            vh.iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteData(list.get(position));
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView text;
            ImageView iv;

        }
    }

    void deleteData(String bookname) {
        String dataText = "";
        try {

            JSONArray arr = new JSONArray(jsonData);
            JSONArray newArr = new JSONArray();
            for (int i = 0; i < arr.length(); i++) {
                if (!arr.getString(i).equals(bookname)) {
                    newArr.put(arr.getString(i));
                }
            }
            if (newArr.length() > 0) {
                dataText = newArr.toString();
            }
            SpUtils.setString(mContext, "jsonData", dataText);
            initList();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    void addData(String bookname) {
        JSONArray arr;
        try {
            if (TextUtils.isEmpty(jsonData)) {
                arr = new JSONArray();
            } else {
                arr = new JSONArray(jsonData);
            }
            arr.put(bookname);
            SpUtils.setString(mContext, "jsonData", arr.toString());
            initList();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
